/**
 * Created by denh on 16/6/20.
 */

var Common = function(){
    this.indexUrl = 'index.php';
    this.serverUrl = '';
    this.qiniuUrl = 'http://static.cyyzjk.com/';
};

Common.prototype = {
    test: function() {
        console.log(this.serverUrl);
    },
    get:function(m, a, data) {
        url = this.url(m, a);
        return this.ajax(url, data, 'get');
    },

    post:function(m, a, data) {
        url = this.url(m, a);
        return this.ajax(url, data, 'post');
    },

    ajax:function(url, data, method) {
        var json = null;

        try {
            var html = '<div class="poploading"><p>正在加载……</p></div>';
            $("body").append(html);
            $.ajax({
                url:url,
                data:data,
                dataType:'json',
                timeout:30000,
                type:method,
                async:false, //默认值: true。默认设置下，所有请求均为异步请求。如果需要发送同步请求，请将此选项设置为 false
                success:function(callback) {
                    //alert( JSON.stringify(callback) );
                    $(".poploading").remove();
                    console.debug(' success callBack:'+callback);
                    if( callback.result>=0 ) {
                        json = callback;
                    } else {
                        var errMsg=Common.prototype.validVar(callback.message)?callback.message:'json error!';
                        json = {"result":-1,"message":errMsg};
                    }
                },

                complete:function() {
                    $(".poploading").remove();
                    if(status == 'timeout'){
                        Common.prototype.showMsgBox('','加载超时，请重新加载');
                    }
                },

                error:function(callback) {
                    $(".poploading").remove();
                    //alert( JSON.stringify(callback) );

                    try {
                        console.debug(' error callBack:'+JSON.stringify(callback));
                        json = eval('('+callback.responseText+')');
                    } catch( ex ) {
                        console.debug('exception:'+ex);
                    }

                    if( json.result ) {
                        // do nothing
                    } else {
                        json = {"result":-1,"datas":{},"message":ex};
                    }
                }
            });
        } catch(ex) {
            json = {"result":-99,"datas":{},"message":ex};
            console.debug(ex);
        }
        return json;
    },

    upload:function(url, id , call) {
        $.ajaxFileUpload({
            url : url ,// 需要链接到服务器地址
            secureuri : false,       //是否启用安全提交,默认为false
            fileElementId : id, //文件选择框的id属性
            dataType : 'json',// 服务器返回的格式，可以是json
            //data : datas,
            success:function(callback) {
                if( callback.result>=0 ) {
                    json = callback;
                } else {
                    var errMsg=Common.prototype.validVar(callback.message)?callback.message:'json error!';
                    json = {"result":-1,"message":errMsg};
                }
                call(json);
            },
            error: function (data, status, e) {
                console.log(data);
                console.log(status);
                console.log(e);
                alert(e);
            }
        });
    },

    url:function(m, a, p) {
        url = this.indexUrl + '?m=' + m + '&a=' + a;
        if (p) {
            url = url + '&' + p;
        }
        return url;
    },

    redirect:function(m, a, p) {
        url = this.url(m, a, p);
        window.location.href= url ;
    },

    urlParam:function(param) {
        var u = '';
        var i = 0;
        for (var p in param) {
            if (i != 0) {
                u += '&';
            }
            u += p + '=' + param[p];
            i++;
        }
        return u;
    },

    /**
     *  校验参数是否为空
     * @param value  校验的值
     * @returns true/false
     *  */
    validVar: function( value ) {
        return typeof(value) != undefined && value != null && value != '';
    },

    /**
     *  展示消息提示
     *  @param {Object} msg   消息内容，不能为空
     */
    showMsgBox : function(msg) {

        var errorMsg = '<div class="errorCon">'+msg+'</div>';
        $("body").prepend(errorMsg); //被选元素开头插入
        $(".errorCon").animate({top:"0"},500);
        setTimeout( '$(".errorCon").animate({top:"-60px"},500);',1000);
        setTimeout( '$(".errorCon").remove();',1500);
    },
      /**
     *  展示消息提示确定键
     *  @param {Object} msg   消息内容，不能为空
     */
    showMsgBox1 : function(msg) {
        var OKMsg = '<div class="OKCondiv"><div class="OKCon">'+msg+'<div class="OKConBtn">确认</div></div></div>';
        $("body").prepend(OKMsg); //被选元素开头插入
        var OKMsg1 = '<div class="opacityinput"></div>';
        $("body").prepend(OKMsg1); //被选元素开头插入
        $(".OKCon").animate({top:"200"},500,"swing");

        //setTimeout( '$(".errorCon").remove();',1500);
        $(".OKConBtn").click(function(){
            $(".OKCon").animate({top:"-200px"},500,"swing");
            setTimeout( '$(".OKCon").remove();',500);
            setTimeout( '$(".opacityinput").remove();',500);
        })
    },
    /**
     * 由中间放大显示提示框
     * @param msg
     */
    showMsgBox2 : function(msg) {
        var OKMsg = '<div class="msgMsgBox2">'+msg+'<div class="OKConBtn">确认</div></div>';
        $("body").prepend(OKMsg); //被选元素开头插入
        var OKMsg2 = '<div class="opacityinput"></div>';
        $("body").prepend(OKMsg2); //被选元素开头插入
        $(".msgMsgBox2").animate({top:"35%", left: '13%', width:'74%', height:'3rem', 'font-size': '0.75rem'}, 100,"swing");

        $(".OKConBtn").click(function(){
            $(".msgMsgBox2").animate({top:"50%", left:'50%', width:'0px', height:'0px', 'font-size': '0px'}, 100,"swing");
            setTimeout( '$(".msgMsgBox2").remove();',100);
            setTimeout( '$(".opacityinput").remove();',100);
        })
    },

    closeWind : function() {
        if (typeof(WeixinJSBridge)=='undefined') {
            window.close();
        } else {
            WeixinJSBridge.invoke('closeWindow',{},function(res){
                return true;
            });
        }
    },

    /**
     * 获取cookie
     * @param key
     * @returns {*}
     */
    getCookie : function(key) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(key + "=");
            if (c_start != -1) {
                c_start = c_start + key.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    },

    /**
     * 设置cookie
     * @param key
     * @param value
     * @param expiredays
     */
    setCookie : function (key, value, expiredays) {
        if (!expiredays) {
            expiredays = 180;
        }
        var date = new Date();
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = key + "=" + value + ";expires=" + exdate.toUTCString();
    },

    /**
     * url加链接
     * @param str
     * @returns {XML|*|string|void}
     * @constructor
     */
    ReplaceUrl : function (str) {
        var urlReg = new RegExp(/https?:(?:\/\/)[^\s|<|>]+/g);
        return str.replace(urlReg, function(word){
            return "<a href='"+word+"'>"+word+"</a>";
        });
    },

    html_encode : function (str) {
        var s = "";
        if (str.length == 0) return "";
        s = str.replace(/&/g, "&gt;");
        s = s.replace(/</g, "&lt;");
        s = s.replace(/>/g, "&gt;");
        s = s.replace(/ /g, "&nbsp;");
        s = s.replace(/\'/g, "&#39;");
        s = s.replace(/\"/g, "&quot;");
        s = s.replace(/\n/g, "<br>");
        return s;
    },

    html_decode : function (str) {
        var s = "";
        if (str.length == 0) return "";
        s = str.replace(/&gt;/g, "&");
        s = s.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&nbsp;/g, " ");
        s = s.replace(/&#39;/g, "\'");
        s = s.replace(/&quot;/g, "\"");
        s = s.replace(/<br>/g, "\n");
        return s;
    },

    //格式化日期
    getDate : function(date, dispalyHour, displayMinute){
        date = new Date(parseInt(date) * 1000);
        var year = date.getFullYear();
        var month = date.getMonth()+1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        if(month < 10){
            month = '0'+month;
        }
        if(day < 10){
            day = '0'+day;
        }
        if(hour < 10){
            hour = '0'+hour;
        }
        if(minute < 10){
            minute = '0'+minute;
        }
        re = year+'-'+month+'-'+day;
        if (dispalyHour != undefined) {
            re += ' ' + hour;
        }
        if (displayMinute != undefined && dispalyHour != undefined ) {
            re += ':' + minute;
        }
        return re;
    },

    getParam : function (key) {
        var reg = new RegExp("(^|&)" + key +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null) {
            return r[2];
        }else{
            return null;
        }
    },

    setSession : function (key, data) {
        return sessionStorage.setItem(key, JSON.stringify(data));
    },

    getSession : function (key) {
        return JSON.parse(sessionStorage.getItem(key));
    },

    net : function() {
        var funArg = [];
        var success = function(){};
        var error = function(err){alert('err:'+err)};
        var interfaceName = '';

        for (i=0; i<arguments.length; i++) {
            if (typeof arguments[i] == "function") {
                funArg.push(arguments[i]);
            } else {
                if (i == 0) {
                    interfaceName = arguments[i];
                } else if(i == 1) {
                    arg = "'"+arguments[i]+"'";
                } else {
                    arg += ",'"+arguments[i]+"'";
                }
            }
        }

        if(funArg.length == 1) {
            success = funArg[0];
        } else if(funArg.length == 2) {
            success = funArg[0];
            error = funArg[1];
        }

        execStr = "client['"+interfaceName+"']("+ arg + "," + success + "," + error + ");";

        var methods = [];
        methods.push(interfaceName);
        var client = hprose.Client.create(this.serverUrl, methods);

        console.log(execStr);
        eval(execStr);
    }

};

var common = new Common();

function weixinShare(title, desc, link, imgUrl, successCallBack) {
    wx.ready(function(){
        wx.onMenuShareAppMessage({
            title: title, // 分享标题
            desc: desc, // 分享描述
            link: link, // 分享链接
            imgUrl: imgUrl, // 分享图标
            type: '', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                // 用户确认分享后执行的回调函数
                if (successCallBack != undefined) {
                    successCallBack();
                }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        wx.onMenuShareTimeline({
            title: title, // 分享标题
            link: link, // 分享链接
            imgUrl: imgUrl, // 分享图标
            success: function () {
                // 用户确认分享后执行的回调函数
                if (successCallBack != undefined) {
                    successCallBack();
                }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });

        wx.onMenuShareQQ({
            title: title, // 分享标题
            desc: desc, // 分享描述
            link: link, // 分享链接
            imgUrl: imgUrl, // 分享图标
            success: function () {
                // 用户确认分享后执行的回调函数
                if (successCallBack != undefined) {
                    successCallBack();
                }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        wx.onMenuShareWeibo({
            title: title, // 分享标题
            desc: desc, // 分享描述
            link: link, // 分享链接
            imgUrl: imgUrl, // 分享图标
            success: function () {
                // 用户确认分享后执行的回调函数
                if (successCallBack != undefined) {
                    successCallBack();
                }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        wx.onMenuShareQZone({
            title: title, // 分享标题
            desc: desc, // 分享描述
            link: link, // 分享链接
            imgUrl: imgUrl, // 分享图标
            success: function () {
                // 用户确认分享后执行的回调函数
                if (successCallBack != undefined) {
                    successCallBack();
                }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
    })
}

function eventStatic(serverUrl, page){
    if ('undefined' == typeof $) {
        return;
    }
    $(document).ready(function(){
        var type = '爱贝儿医公众号';

        $.post(serverUrl, {page:page, key:'进入页面', keyExt:'', type:type}, function(re){
            console.log(re);
        });

        $("[tongji='aibei']").click(function(){
            var key    = $(this).attr('key');
            var keyExt = $(this).attr('keyExt');
            var url    = $(this).attr('url');
            if (!page) {
                page = document.documentURI;
            }
            if (keyExt == undefined) {
                keyExt = '';
            }
            console.log(page);console.log(key);console.log(keyExt);
            $.post(serverUrl, {page:page, key:key, keyExt:keyExt, type:type}, function(re){
                console.log(re);
                if (url) {
                    window.location.href = url;
                }
            });
            if (url) {
                window.location.href = url;
            }
        });
    });
}
